package com.mine.frame.mylandemo.ui

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import com.blankj.utilcode.util.*
import com.mine.frame.common.base.BaseActivity
import com.mine.frame.common.empty.EmptyPresenter
import com.mine.frame.common.empty.IEmpty
import com.mine.frame.mylandemo.R
import com.swallowsonny.convertextlibrary.hex2ByteArray
import com.swallowsonny.convertextlibrary.toHexString
import com.third.device.mg.serialport.listener.MGNettyConnectListener
import com.third.device.mg.serialport.utils.send.MGSendUtils
import kotlinx.android.synthetic.main.atv_test_empty.*
import kotlinx.android.synthetic.main.layout_connect.*

/**
 * @Date 2022/4/11
 * Description:测试连接
 */
class TestConnectAtv : BaseActivity<IEmpty, EmptyPresenter>(), IEmpty, MGNettyConnectListener {
    /*当前连接的IP地址 和 端口号*/
    private var ipStr = ""
    private var port = 61233

    override fun initLayoutId(): Int = R.layout.atv_test_empty

    override fun initPresenter(): EmptyPresenter = EmptyPresenter(this)


    override fun initLayoutAfter(savedInstanceState: Bundle?) {
        ipStr = intent?.getStringExtra("sel-ip").toString()
        edtIP.text = Editable.Factory.getInstance().newEditable(ipStr)
        ClickUtils.applySingleDebouncing(btnSend) {
            if (checkIp()){
                val data = "12:34:56:78:9A:BC:DE:F0".replace(":", "").hex2ByteArray()
                MGSendUtils.instance.sentCommand(ipStr ,port ,data)
            }
        }
        MGSendUtils.instance.initUtils(application ,this)
    }


    private fun checkIp():Boolean{
        KeyboardUtils.hideSoftInput(this)
        if (edtIP.text.isNullOrEmpty()) {
            SnackbarUtils.with(edtIP).setMessage("请输入IP地址").showWarning()
            return false
        } else {
            ipStr = edtIP.text.toString()
        }
        if (edtPort.text.isNullOrEmpty()) {
            SnackbarUtils.with(edtIP).setMessage("请输入端口号").showWarning()
            return false
        } else {
            port = edtPort.text.toString().toInt()
            if (port < 1 || port > 65535) {
                SnackbarUtils.with(edtIP).setMessage("端口号异常(1,65535)").showWarning()
                return false
            }
        }
        if (ipStr.isEmpty()) {
            SnackbarUtils.with(edtIP).setMessage("IP地址异常").showError()
            return false
        }
        return true
    }



    /**
     * 更新指示器
     */
    private fun updateIndicator(connect: Boolean) {
        val resId = if (connect) {
            R.drawable.blue_circle
        } else {
            R.drawable.red_circle
        }
        viewIndicator.setBackgroundResource(resId)
    }


    override fun onDestroy() {
        super.onDestroy()
        MGSendUtils.instance.disposableUtils()
    }


    /*==========================MGNettyConnectListener=========================================*/
    override fun connectBack(ip: String, port: Int) {
        updateIndicator(true)
        SnackbarUtils.with(btnConnect).setMessage("Netty连接成功，可以发消息").showSuccess(true)
    }

    override fun disconnectBack(ip: String, port: Int) {
        updateIndicator(false)
        SnackbarUtils.with(btnConnect).setMessage("Netty已经断开连接").showError(true)
    }

    @SuppressLint("SetTextI18n")
    override fun readBack(ip: String, port: Int, result: ByteArray) {
        SnackbarUtils.with(btnConnect).setMessage("收到消息").showSuccess(true)
        tvInfo.text = "接收:${result.toHexString(true)}"
    }

    override fun writeBack(ip: String, port: Int, successful: Boolean, data: ByteArray) {
        if (successful) {
            SnackbarUtils.with(btnConnect).setMessage("发送成功").showSuccess(true)
        } else {
            SnackbarUtils.with(btnConnect).setMessage("发送失败").showError(true)
        }
    }

    override fun errorBack(ip: String, port: Int, error: Throwable) {
        updateIndicator(false)
        error.message?.let {
            showErr(it)
            LogUtils.e(it)
        }
    }
    /*==========================MGNettyConnectListener=========================================*/
}